﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;

namespace NeatlyEditor
{
    public static class NeatlyAssetBundleCheck
    {
        private static readonly Dictionary<string, int> RecordBundleMap = new();

        public static void CheckAssetBundleDependency()
        {
            RecordBundleMap.Clear();
            var assetBundle = AssetBundle.LoadFromFile(Path.Combine(NeatlyEditorConfig.PATH_TEMP_BUNDLE, NeatlyConfig.NAME_MANIFEST));
            AssetBundleManifest manifest = assetBundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest");
            assetBundle.Unload(false);
            CheckAssetBundleDependency(manifest);
        }
        public static void CheckAssetBundleDependency(AssetBundleManifest manifest)
        {
            RecordBundleMap.Clear();
            var assetBundleList = manifest.GetAllAssetBundles().ToList();
            while (true)
            {
                int addCount = 0;
                for (int i = assetBundleList.Count - 1; i >= 0; i--)
                {
                    var bundleName = assetBundleList[i];
                    var dependencyArray = manifest.GetAllDependencies(bundleName);
                    if (!CheckDependArray(dependencyArray)) continue;
                    RecordBundleMap.Add(bundleName, 1);
                    addCount++;
                    assetBundleList.RemoveAt(i);
                }
                if (addCount != 0) continue;
                foreach (var s in assetBundleList)
                {
                    Debug.LogError($"AssetBundle 嵌套依赖:{s}");
                }
                Debug.Log($"AssetBundle依赖检测完成...");
                return;
            }
        }

        private static bool CheckDependArray(string[] dependencyArray)
        {
            if (dependencyArray.Length <= 0) return true;
            foreach (var bundleName in dependencyArray)
            {
                if (!RecordBundleMap.ContainsKey(bundleName))
                {
                    return false;
                }
            }
            return true;
        }
    }
}